<template>
  <div class="relative">
    <!-- 新增修改检查单 -->
    <el-form :model="orderForm" :rules="rules" ref="formRef" class="order">
      <el-descriptions border :column="2">
        <el-descriptions-item
          label="检查单号"
          width="100px"
          label-align="center"
        >
          <el-form-item prop="checkCode">
            <el-input
              v-model="orderForm.checkCode"
              placeholder="请点击选择检查单号"
              readonly
              @click="handleChangeCheck"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item
          label="客户名称"
          width="100px"
          label-align="center"
        >
          <template #label>
            <span class="text-red-500">*</span>
            <span>客户名称</span>
          </template>
          <el-form-item prop="customerName">
            <el-input
              v-model="orderForm.customerName"
              placeholder="请点击选择客户名称"
              style="width: 100%"
              clearable
              readonly
              disabled
              @click="handleChangeCustomer"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item width="100px" label-align="center">
          <template #label>
            <span class="text-red-500">*</span>
            <span>是否加工</span>
          </template>
          <el-form-item prop="isProcess">
            <el-select
              v-model="orderForm.isProcess"
              filterable
              style="width: 100%"
            >
              <el-option label="加工" :value="1"></el-option>
              <el-option label="不加工" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item width="100px" label-align="center">
          <template #label>
            <span class="text-red-500">*</span>
            <span>业务员</span>
          </template>
          <el-form-item prop="businessUserId">
            <el-select
              v-model="orderForm.businessUserId"
              filterable
              placeholder="请选择业务员"
              style="width: 100%"
            >
              <el-option
                v-for="item in staffList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="销售时间" label-align="center">
          <el-form-item prop="businessTime">
            <el-date-picker
              v-model="orderForm.businessTime"
              type="datetime"
              placeholder="请选择时间"
              format="YYYY-MM-DD HH:mm"
              value-format="x"
              style="width: 100%"
            />
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="标准总价(元)" label-align="center">
          <div>
            {{ orderForm.totalAmount ? orderForm.totalAmount.toFixed(2) : 0 }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="分项优惠总额(元)" label-align="center">
          <div>
            {{
              orderForm.subTotalDiscount
                ? orderForm.subTotalDiscount.toFixed(2)
                : 0
            }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="整单直减(元)" label-align="center">
          <el-input-number
            v-model="orderForm.totalDiscount"
            placeholder="请输入直减金额"
            style="width: 100%"
            :precision="2"
            :min="0"
            :max="orderForm.receivableAmount"
            @input="computeTotal(1)"
            :title="
              orderForm.paidAmount <= orderForm.totalDiscount
                ? '整单直减不能高于应收金额'
                : ''
            "
          />
        </el-descriptions-item>
        <el-descriptions-item label-align="center">
          <template #label>
            <div class="flex items-center justify-center">
              <el-popover placement="bottom" trigger="hover" width="440px">
                <template #reference>
                  <el-icon style="cursor: pointer; color: #1a7de3">
                    <QuestionFilled />
                  </el-icon>
                </template>
                <el-tag type="info">标准总价</el-tag>
                -
                <el-tag type="warning">分项优惠总额</el-tag>
                -
                <el-tag type="danger">整单直减</el-tag>
                =
                <el-tag type="success">应收金额</el-tag>
              </el-popover>
              <span>应收金额(元)</span>
            </div>
          </template>
          {{ orderForm.paidAmount ? orderForm.paidAmount.toFixed(2) : 0 }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" label-align="center">
          <el-form-item prop="remark">
            <el-input
              v-model="orderForm.remark"
              placeholder="请输入备注"
              style="width: 100%"
              type="textarea"
              :rows="1"
            />
          </el-form-item>
        </el-descriptions-item>
      </el-descriptions>
    </el-form>

    <el-card class="product_order">
      <template #header>
        <div class="w-full flex justify-between items-center">
          <div>销售明细</div>
          <!-- <el-button type="primary" @click="handleChangeProduct">
            添加商品
          </el-button> -->
          <el-button type="primary">
            <el-dropdown>
              <span class="el-dropdown-link text-white">
                添加商品
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-button
                      icon="Plus"
                      class="w-full"
                      @click="handleChangeProduct(1)"
                      >左眼商品</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      icon="Plus"
                      class="w-full"
                      @click="handleChangeProduct(2)"
                      >右眼商品</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      icon="Plus"
                      class="w-full"
                      @click="handleChangeProduct(3)"
                      >综合商品</el-button
                    >
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-button>
        </div>
      </template>

      <el-table
        :data="tableData"
        style="width: 100%; height: calc(100vh - 25.5rem)"
      >
        <el-table-column label="商品名称" fixed="left" width="200">
          <template #default="{ row }">
            <div>
              {{ row.goodsTitle }}
            </div>
            <div>
              {{ row.categoryName + "_" + row.typeName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品规格" width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.specsDescription }}
          </template>
        </el-table-column>
        <el-table-column label="零售单价(元)" width="180">
          <template #default="{ row }">
            <el-input-number
              v-model="row.priceAtOrder"
              placeholder="请输入单价"
              :precision="2"
              :min="0"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="售出数量(件)" width="180">
          <template #default="{ row }">
            <el-input-number v-model="row.count" :min="0" />
          </template>
        </el-table-column>
        <el-table-column label="分项价(元)" align="center" width="100">
          <template #default="{ row }">
            {{
              new Decimal(row.priceAtOrder).mul(new Decimal(row.count))
                ? new Decimal(row.priceAtOrder)
                    .mul(new Decimal(row.count))
                    .toNumber()
                    .toFixed(2)
                : 0
            }}
          </template>
        </el-table-column>
        <el-table-column label="分项直减(元)" width="180">
          <template #default="{ row }">
            <el-input-number
              v-model="row.discount"
              placeholder="请输入直减金额"
              :precision="2"
              :min="0"
              @change="handle_item_lapse(row)"
            ></el-input-number>
          </template>
        </el-table-column>
        <!-- <el-table-column label="分项优惠(元)" align="center" width="180">
          <template #default="{ row }">
            {{ row.subItemDiscount ? row.subItemDiscount.toFixed(2) : 0 }}
          </template>
        </el-table-column> -->
        <el-table-column label="分项应收(元)" align="center" width="180">
          <template #default="{ row }">
            {{ row.amount ? row.amount.toFixed(2) : 0 }}
          </template>
        </el-table-column>
        <el-table-column label="类别" align="center">
          <template #default="{ row }">
            <el-tag
              :type="
                row.eyeType == 2
                  ? 'primary'
                  : row.eyeType == 3
                  ? 'success'
                  : 'info'
              "
            >
              {{
                row.eyeType == 1 ? "左眼" : row.eyeType == 2 ? "右眼" : "综合"
              }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" :width="120" align="center">
          <template #default="{ row }">
            <el-button type="danger" @click="handleRemove(row.id)" link>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div class="flex justify-end items-center mt-1">
      <el-button @click="handleCancel(0)">取消</el-button>
      <el-button type="primary" @click="handleSubmit(1)">
        {{ orderForm.isProcess == 1 ? "待加工" : "待出库" }}
      </el-button>
      <el-button type="primary" @click="handleSubmit(2)">
        {{ orderForm.isProcess == 1 ? "已加工" : "已出库" }}
      </el-button>
    </div>

    <el-drawer
      v-model="check_drawer"
      destroy-on-close
      size="80%"
      title="选择检查单号"
    >
      <ChangeCheck
        :detailForm="orderForm"
        :flag="true"
        @handleBack="handleChangeCheckSuccess"
      />
    </el-drawer>

    <el-drawer
      v-model="customer_drawer"
      destroy-on-close
      size="80%"
      title="选择客户"
    >
      <ChangeCustomer />
    </el-drawer>

    <el-drawer
      v-model="product_drawer"
      destroy-on-close
      size="80%"
      title="选择商品"
    >
      <ChangeProduct @handleChangeOneProduct="handleChangeProductSuccess" />
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, watchEffect } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/pinia";
import { storeToRefs } from "pinia";
import { cloneDeep } from "lodash";
import { watchStorage, setStorageWithEvent } from "@/utils/GlobalMonitoring.js";
import Decimal from "decimal.js";
import ChangeProduct from "@/components/ChangeProduct.vue";
import ChangeCheck from "@/components/ChangeCheck.vue";
import ChangeCustomer from "@/components/ChangeCustomer.vue";
import { handleApiResponse } from "@/utils/request.js";
import { GetOrganizeEmployeeList } from "../../../../../wailsjs/go/api/CustomerApi";
import {
  CreateSaleOrder,
  CreateGlassesStoreUnfinishedOrder,
} from "../../../../../wailsjs/go/api/OrderApi";

const useStore = useUserStore();
const { checkDetailForm } = storeToRefs(useStore);

onMounted(() => {
  getStaffList();

  const now = new Date();
  now.setSeconds(0);
  now.setMilliseconds(0);
  orderForm.value.businessTime = now.getTime();

  orderForm.value.checkCode = checkDetailForm.value.code;
  orderForm.value.customerId = checkDetailForm.value.customerId;
  orderForm.value.customerName = checkDetailForm.value.customerName;
});

const emit = defineEmits(["handleBack"]);

const formRef = ref(null);
const orderForm = ref({
  checkCode: "",
  customerId: null,
  customerName: "",
  isProcess: 1,
  businessUserId: null, //业务员
  businessTime: null, //销售时间
  remark: "", //备注
});

const tableData = ref([]);

const rules = ref({
  customerName: [
    {
      required: true,
      message: "请选择客户名称",
    },
  ],
  isProcess: [
    {
      required: true,
      message: "请选择业务员",
    },
  ],
  businessUserId: [
    {
      required: true,
      message: "请选择业务员",
    },
  ],
});

// 1.选择检查单号
const check_drawer = ref(false);
const handleChangeCheck = () => {
  check_drawer.value = true;
};
const handleChangeCheckSuccess = (val) => {
  // console.log(val);
  orderForm.value.detailId = val.id;
  orderForm.value.checkCode = val.code;
  orderForm.value.customerId = val.customerId;
  orderForm.value.customerName = val.customerName;
  check_drawer.value = false;
};

// 2.选择客户
const customer_drawer = ref(false);
const handleChangeCustomer = () => {
  customer_drawer.value = true;
};

// 3.选择商品
const product_drawer = ref(false);
const eye_type = ref(1);
const handleChangeProduct = (type) => {
  eye_type.value = type;
  product_drawer.value = true;
};
const handleChangeProductSuccess = (val) => {
  val.goodsSpecId = val.id;
  const data = new Date();
  val.id = data.getTime();
  val.specsDescription = val.specsDescription.join(",");
  val.ignoreStock = true;
  val.goodId = val.goodsId;
  val.eyeType = cloneDeep(eye_type.value);
  tableData.value.push(val);
  product_drawer.value = false;
};

// 删除单个商品
const handleRemove = (id) => {
  ElMessageBox.confirm("你确定要删除这条商品吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    tableData.value = tableData.value.filter((item) => item.id !== id);
  });
};

const staffList = ref([]); // 业务员列表
async function getStaffList() {
  handleApiResponse(() =>
    GetOrganizeEmployeeList({ page: 1, pageSize: 1234 })
  ).then((res) => {
    if (res.code == 0) {
      staffList.value = res.data.list || [];
    }
  });
}

// 处理分项直减  禁止大于总价
const handle_item_lapse = (row) => {
  let total_price = new Decimal(row.priceAtOrder).mul(row.count).toNumber();

  if (+row.discount >= +total_price) {
    row.discount = +total_price;
    ElMessage.warning("分项直减不能大于分项总价");
  }
};

const discountNumber = ref(100);
// 处理所有价格的计算
function computeTotal(type) {
  if (type) {
    if (orderForm.value.receivableAmount < orderForm.value.totalDiscount) {
      ElMessage.warning("整单直减不能高于应收金额");
      orderForm.value.totalDiscount = 0;
    }
  }
  orderForm.value.totalAmount = 0;
  orderForm.value.subTotalDiscount = 0;
  orderForm.value.receivableAmount = 0;

  orderForm.value.paidAmount = 0;
  orderForm.value.quantity = 0;

  tableData.value.forEach((item) => {
    // 防止客户输入了空的解决办法
    item.priceAtOrder = item.priceAtOrder ? item.priceAtOrder : 1;
    item.count = item.count ? item.count : 1;
    item.discount = item.discount ? item.discount : 0;

    // 折扣  0.85
    item.vipDiscountRate = discountNumber.value;
    let vip = new Decimal(
      discountNumber.value == 100
        ? 1
        : new Decimal(discountNumber.value).div(new Decimal(100))
    );

    // 1.分项优惠    单价*数量-单价*数量*折扣(0.85)+分项优惠discount
    item.subItemDiscount = 0;

    item.subItemDiscount = new Decimal(item.priceAtOrder)
      .mul(new Decimal(item.count))
      .sub(
        new Decimal(item.priceAtOrder)
          .mul(new Decimal(item.count))
          .mul(new Decimal(vip))
      )
      .add(item.discount)
      .toString();
    item.subItemDiscount = +item.subItemDiscount;

    // 2.分项应收
    item.amount = new Decimal(item.priceAtOrder)
      .mul(new Decimal(item.count))
      .mul(new Decimal(vip))
      .sub(item.discount)
      .toString();
    item.amount = +item.amount;

    // 一、计算标准总价
    let total_price = new Decimal(item.priceAtOrder)
      .mul(new Decimal(item.count))
      .toString();
    orderForm.value.totalAmount += +total_price;

    // 二、计算分项优惠总价
    orderForm.value.subTotalDiscount += +item.subItemDiscount;

    // 三、分项应收 (未计算总额直减)
    orderForm.value.receivableAmount += +item.amount;

    // 四、商品总数量
    orderForm.value.quantity += +item.count;
  });

  // 五、应收金额
  orderForm.value.totalDiscount = orderForm.value.totalDiscount
    ? orderForm.value.totalDiscount
    : 0;
  orderForm.value.paidAmount =
    new Decimal(orderForm.value.receivableAmount).sub(
      new Decimal(orderForm.value.totalDiscount)
    ) || 0;
}

const handleCancel = (val = 0) => {
  if (val == 1) {
    setStorageWithEvent("refresh_history_order");
  }
  emit("handleBack", val);
};
// 提交
const handleSubmit = (type) => {
  formRef.value.validate((valid) => {
    if (!valid) return;

    // return console.log(init_AllPrice());
    if (type == 1) {
      handleApiResponse(() =>
        CreateGlassesStoreUnfinishedOrder(init_AllPrice())
      ).then((res) => {
        if (res.code == 0) {
          ElMessage.success("提交成功");
          handleCancel(1);
        }
      });
    } else if (type == 2) {
      handleApiResponse(() => CreateSaleOrder(init_AllPrice())).then((res) => {
        if (res.code == 0) {
          ElMessage.success("提交成功");
          handleCancel(1);
        }
      });
    }
  });
};

//封装一个方法，处理后端需要的价格数据格式(不能有小数点)
function init_AllPrice() {
  let form = cloneDeep(orderForm.value);
  form.totalAmount = mulTen(form.totalAmount);
  form.subTotalDiscount = mulTen(form.subTotalDiscount);
  form.receivableAmount = mulTen(form.receivableAmount);
  form.totalDiscount = mulTen(form.totalDiscount);
  form.paidAmount = mulTen(form.paidAmount);

  if (form.businessUserId)
    form.businessUserName = staffList.value.find((item) => {
      return item.id == form.businessUserId;
    }).name;

  if (form.businessTime) {
    form.businessTime = form.businessTime / 1000;
  }

  let cloneList = cloneDeep(tableData.value);
  cloneList.forEach((item) => {
    item.priceAtOrder = mulTen(item.priceAtOrder);
    item.discount = mulTen(item.discount);
    item.subItemDiscount = mulTen(item.subItemDiscount);
    item.amount = mulTen(item.amount);

    item.ignoreStock = item.ignoreStock ? 1 : 2;
  });

  return {
    ...form,
    orderItems: cloneList,
  };
}

/** 
  @param {Number} num
  @return 数字乘以100后的结果
*/
function mulTen(num) {
  let initNum = new Decimal(num).mul(new Decimal(100)).toString();
  return +initNum;
}

watchEffect(() => {
  computeTotal();
});
</script>

<style scoped lang="scss">
.order :deep(.el-form-item) {
  margin-bottom: 0;
}

.product_order {
  @apply text-[0.8rem] mt-2;
  :deep(.el-card__header) {
    @apply px-2 py-1;
  }
}
</style>